<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, nextTick, watch } from "vue";
import { getCurrentWindow } from "@tauri-apps/api/window";
import { useTodoStore } from "../stores/todo";
import { useSettingsStore } from "../stores/settings";
import AutoResizeTextarea from "../components/AutoResizeTextarea.vue";
import dayjs from "dayjs";
import { useAutoAnimate } from "@formkit/auto-animate/vue";

const todoStore = useTodoStore();
const settingsStore = useSettingsStore();
const currentWindow = getCurrentWindow();
const [todoListRef] = useAutoAnimate({ duration: 500 });

// 新增：用于检测是否需要固定底部按钮
const todoListContainer = ref<HTMLElement | null>(null);
const isOverflowing = ref(false);
const addButtonHeight = ref(0);
const addButtonRef = ref<HTMLElement | null>(null);

const editingId = ref<string | null>(null);
const editingContent = ref("");
const isAddingNew = ref(false);
const newTodoContent = ref("");
const showPriorityPopover = ref<string | null>(null); // 当前显示 popover 的待办 ID
const popoverDirection = ref<Record<string, "up" | "down">>({}); // 每个待办项的 popover 方向

// 获取悬浮窗口待办：未完成的待办 + 今天完成的待办
const floatingTodos = computed(() => {
  const today = dayjs().format("YYYY-MM-DD");

  const filtered = todoStore.todos.filter((todo) => {
    // 未完成的待办：显示
    if (!todo.completed) {
      return true;
    }

    // 已完成的待办：只显示今天完成的
    if (todo.completedAt) {
      const completedDate = dayjs(todo.completedAt).format("YYYY-MM-DD");
      return completedDate === today;
    }

    // 没有完成时间记录的已完成待办：不显示
    return false;
  });

  // 使用 store 的排序方法
  return todoStore.getSortedTodos(filtered);
});

// 判断是否为今日待办
function isToday(date: string) {
  return date === dayjs().format("YYYY-MM-DD");
}

// 格式化日期显示
function formatDate(date: string) {
  const d = dayjs(date);
  return d.format("MM月DD日");
}

onMounted(async () => {
  await todoStore.loadTodos();
  await settingsStore.loadSettings();

  // 给 html 标签添加悬浮窗口样式
  const htmlElement = document.documentElement;
  htmlElement.style.borderRadius = "20px";
  htmlElement.style.overflow = "hidden";

  // 监听全局点击事件，关闭 popover
  const handleClickOutside = () => {
    if (showPriorityPopover.value) {
      showPriorityPopover.value = null;
    }
  };
  document.addEventListener("click", handleClickOutside);

  // 监听窗口显示事件，重新加载数据
  const unlisten = await currentWindow.onFocusChanged(
    async ({ payload: focused }) => {
      if (focused) {
        await todoStore.loadTodos();
      }
    }
  );

  // 初始检查溢出
  nextTick(() => {
    checkOverflow();
  });

  // 监听窗口大小变化
  window.addEventListener("resize", checkOverflow);

  // 保存 unlisten 函数以便清理
  onUnmounted(() => {
    unlisten();
    document.removeEventListener("click", handleClickOutside);
    window.removeEventListener("resize", checkOverflow);
    // 清理样式
    const htmlElement = document.documentElement;
    htmlElement.style.borderRadius = "";
    htmlElement.style.boxShadow = "";
    htmlElement.style.overflow = "";
  });
});

// 开始添加待办
function startAddTodo() {
  if (!isAddingNew.value) {
    isAddingNew.value = true;
    newTodoContent.value = "";
  }
}

// 添加待办
function addNewTodo() {
  if (newTodoContent.value.trim()) {
    todoStore.addTodo(newTodoContent.value.trim());
  }
  isAddingNew.value = false;
  newTodoContent.value = "";
  nextTick(() => {
    checkOverflow();
  });
}

// 取消添加
function cancelAdd() {
  isAddingNew.value = false;
  newTodoContent.value = "";
  nextTick(() => {
    checkOverflow();
  });
}

// 开始编辑
function startEdit(id: string, content: string) {
  editingId.value = id;
  editingContent.value = content;
}

// 保存编辑
function saveEdit() {
  if (editingId.value && editingContent.value.trim()) {
    todoStore.updateTodo(editingId.value, {
      content: editingContent.value.trim(),
    });
  }
  editingId.value = null;
  editingContent.value = "";
}

// 取消编辑
function cancelEdit() {
  editingId.value = null;
  editingContent.value = "";
}

// 切换完成状态
function toggleComplete(id: string) {
  todoStore.toggleComplete(id);
  nextTick(() => {
    checkOverflow();
  });
}

// 切换优先级 popover
function togglePriorityPopover(id: string, event: MouseEvent) {
  if (showPriorityPopover.value === id) {
    showPriorityPopover.value = null;
  } else {
    showPriorityPopover.value = id;

    // 检测 popover 应该向上还是向下显示
    nextTick(() => {
      const target = event.target as HTMLElement;
      const todoItem = target.closest(".todo-item");
      if (todoItem) {
        const rect = todoItem.getBoundingClientRect();
        const windowHeight = window.innerHeight;
        const spaceBelow = windowHeight - rect.bottom;
        const popoverHeight = 180; // popover 大约高度

        // 如果下方空间不足，向上显示
        popoverDirection.value[id] = spaceBelow < popoverHeight ? "up" : "down";
      }
    });
  }
}

// 设置优先级并关闭 popover
function setPriorityAndClose(id: string, priority?: "high" | "medium" | "low") {
  todoStore.setPriority(id, priority);
  showPriorityPopover.value = null;
}

// 获取优先级颜色类名
function getPriorityClass(priority?: string) {
  if (!priority) return "";
  return `priority-${priority}`;
}

// 获取 popover 方向
function getPopoverDirection(id: string): "up" | "down" {
  return popoverDirection.value[id] || "down";
}

// 检查列表是否溢出
function checkOverflow() {
  if (todoListContainer.value) {
    const container = todoListContainer.value;
    const wasOverflowing = isOverflowing.value;
    isOverflowing.value = container.scrollHeight > container.clientHeight;

    // 如果溢出状态发生变化，在下一帧更新按钮高度
    if (wasOverflowing !== isOverflowing.value) {
      nextTick(() => {
        if (addButtonRef.value && isOverflowing.value) {
          addButtonHeight.value = addButtonRef.value.offsetHeight;
        } else {
          addButtonHeight.value = 0;
        }
      });
    } else if (addButtonRef.value && isOverflowing.value) {
      addButtonHeight.value = addButtonRef.value.offsetHeight;
    }
  }
}

// 在待办列表变化时检查溢出
const floatingTodosWithCheck = computed(() => {
  const todos = floatingTodos.value;
  nextTick(() => {
    checkOverflow();
  });
  return todos;
});

// 监听添加新待办状态变化
watch(isAddingNew, () => {
  nextTick(() => {
    checkOverflow();
  });
});
</script>

<template>
  <div class="floating-window-wrapper" data-tauri-drag-region>
    <div class="floating-window">
      <!-- 待办列表 -->
      <div
        class="todo-list"
        ref="todoListContainer"
        :style="{
          paddingBottom: isOverflowing ? `${addButtonHeight + 6}px` : '0',
        }"
      >
        <div ref="todoListRef">
          <div
            v-if="floatingTodosWithCheck.length === 0 && !isAddingNew"
            class="empty-state"
          >
            暂无待办事项
          </div>
          <div
            v-for="todo in floatingTodosWithCheck"
            :key="todo.id"
            class="todo-item"
          >
            <!-- 优先级色条 -->
            <div
              class="priority-bar"
              :class="getPriorityClass(todo.priority)"
              title="优先级标识"
            ></div>

            <input
              type="checkbox"
              :checked="todo.completed"
              @change="toggleComplete(todo.id)"
              class="checkbox"
            />
            <div
              v-if="editingId !== todo.id"
              @click="startEdit(todo.id, todo.content)"
              class="todo-content-wrapper"
            >
              <div class="todo-content" :class="{ completed: todo.completed }">
                {{ todo.content }}
              </div>
              <div v-if="!isToday(todo.date)" class="todo-date">
                {{ formatDate(todo.date) }}
              </div>
            </div>
            <AutoResizeTextarea
              v-else
              v-model="editingContent"
              @blur="saveEdit"
              @enter="saveEdit"
              @esc="cancelEdit"
              class="todo-input"
              :autofocus="true"
            />
            <!-- 优先级选择器 -->
            <div class="priority-selector-wrapper">
              <div
                class="priority-selector"
                @click.stop="togglePriorityPopover(todo.id, $event)"
                title="点击选择优先级"
              >
                <div
                  class="priority-square"
                  :class="getPriorityClass(todo.priority)"
                ></div>
              </div>

              <!-- 优先级 Popover -->
              <div
                v-if="showPriorityPopover === todo.id"
                class="priority-popover"
                :class="{ 'popover-up': getPopoverDirection(todo.id) === 'up' }"
                @click.stop
              >
                <button
                  @click="setPriorityAndClose(todo.id, 'high')"
                  class="priority-option"
                  :class="{ active: todo.priority === 'high' }"
                >
                  <span class="priority-dot high"></span>
                  <span class="priority-label">高优先级</span>
                </button>
                <button
                  @click="setPriorityAndClose(todo.id, 'medium')"
                  class="priority-option"
                  :class="{ active: todo.priority === 'medium' }"
                >
                  <span class="priority-dot medium"></span>
                  <span class="priority-label">中优先级</span>
                </button>
                <button
                  @click="setPriorityAndClose(todo.id, 'low')"
                  class="priority-option"
                  :class="{ active: todo.priority === 'low' }"
                >
                  <span class="priority-dot low"></span>
                  <span class="priority-label">低优先级</span>
                </button>
                <button
                  @click="setPriorityAndClose(todo.id, undefined)"
                  class="priority-option"
                  :class="{ active: !todo.priority }"
                >
                  <span class="priority-dot none"></span>
                  <span class="priority-label">无优先级</span>
                </button>
              </div>
            </div>
          </div>

          <!-- 新增待办项 -->
          <div v-if="isAddingNew" class="todo-item">
            <div class="checkbox-placeholder"></div>
            <AutoResizeTextarea
              v-model="newTodoContent"
              @enter="addNewTodo"
              @blur="addNewTodo"
              @esc="cancelAdd"
              placeholder="输入待办内容..."
              class="todo-input"
              :autofocus="true"
            />
          </div>

          <!-- 添加待办按钮 - 未溢出时在列表内 -->
          <div
            v-if="!isAddingNew && !isOverflowing"
            class="todo-item add-todo-btn"
            @click="startAddTodo"
          >
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="16"
              height="16"
              viewBox="0 0 24 24"
              fill="none"
              stroke="currentColor"
              stroke-width="2"
              stroke-linecap="round"
              stroke-linejoin="round"
              class="add-icon"
            >
              <line x1="12" y1="5" x2="12" y2="19"></line>
              <line x1="5" y1="12" x2="19" y2="12"></line>
            </svg>
            <span class="add-text">添加待办</span>
          </div>
        </div>
      </div>

      <!-- 添加待办按钮 - 溢出时固定在底部 -->
      <div
        v-if="!isAddingNew && isOverflowing"
        ref="addButtonRef"
        class="todo-item add-todo-btn fixed-add-btn"
        @click="startAddTodo"
      >
        <svg
          xmlns="http://www.w3.org/2000/svg"
          width="16"
          height="16"
          viewBox="0 0 24 24"
          fill="none"
          stroke="currentColor"
          stroke-width="2"
          stroke-linecap="round"
          stroke-linejoin="round"
          class="add-icon"
        >
          <line x1="12" y1="5" x2="12" y2="19"></line>
          <line x1="5" y1="12" x2="19" y2="12"></line>
        </svg>
        <span class="add-text">添加待办</span>
      </div>
    </div>
  </div>
</template>

<style scoped>
.floating-window-wrapper {
  width: 100vw;
  height: 100vh;
  padding: 16px 0;
}

.floating-window {
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  overflow: hidden;
}

.drag-region {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  z-index: 0;
  pointer-events: auto;
  -webkit-user-select: none;
  user-select: none;
}

.todo-list {
  flex: 1;
  overflow-y: auto;
  padding: 0;
  position: relative;
  z-index: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  pointer-events: none;
  /* 隐藏滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE and Edge */
}

.todo-list > div {
  width: 100%;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 6px;
}

.todo-list::-webkit-scrollbar {
  display: none; /* Chrome, Safari and Opera */
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  color: var(--text-secondary);
  font-size: 14px;
  pointer-events: auto;
  cursor: pointer;
}

.todo-item {
  position: relative;
  width: calc(100% - 20px);
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 6px 16px;
  background: var(--bg-secondary);
  border-radius: 12px;
  margin-bottom: 0;
  pointer-events: auto;
}

.todo-item:hover {
  background: var(--bg-secondary);
}

.todo-item .priority-bar {
  position: absolute;
  left: 0;
  top: 0;
  bottom: 0;
  width: 3px;
  border-radius: 12px 0 0 12px;
  cursor: pointer;
  transition: width 0.2s ease;
  z-index: 1;
}

.todo-item .priority-bar:hover {
  width: 5px;
}

.priority-bar.priority-high {
  background: #ef4444;
}

.priority-bar.priority-medium {
  background: #f59e0b;
}

.priority-bar.priority-low {
  background: #3b82f6;
}

/* 优先级选择器 */
.priority-selector-wrapper {
  position: relative;
  flex-shrink: 0;
}

.priority-selector {
  opacity: 0;
  transition: opacity 0.2s ease;
  cursor: pointer;
  padding: 2px;
}

.todo-item:hover .priority-selector {
  opacity: 1;
}

.priority-square {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  background: var(--border-color);
  transition: all 0.2s ease;
}

.priority-square.priority-high {
  background: #ef4444;
}

.priority-square.priority-medium {
  background: #f59e0b;
}

.priority-square.priority-low {
  background: #3b82f6;
}

.priority-selector:hover .priority-square {
  transform: scale(1.1);
}

/* 优先级 Popover */
.priority-popover {
  position: absolute;
  right: 0;
  top: calc(100% + 4px);
  background: var(--bg-primary);
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 4px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  min-width: 120px;
  display: flex;
  flex-direction: column;
  gap: 2px;
}

/* 向上弹出的 Popover */
.priority-popover.popover-up {
  top: auto;
  bottom: calc(100% + 4px);
}

.priority-option {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 10px;
  background: transparent;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  transition: background 0.2s;
  text-align: left;
  color: var(--text-primary);
}

.priority-option:hover {
  background: var(--bg-secondary);
}

.priority-option.active {
  background: var(--bg-secondary);
}

.priority-dot {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  flex-shrink: 0;
}

.priority-dot.high {
  background: #ef4444;
}

.priority-dot.medium {
  background: #f59e0b;
}

.priority-dot.low {
  background: #3b82f6;
}

.priority-dot.none {
  background: var(--border-color);
}

.priority-label {
  font-size: 13px;
  white-space: nowrap;
}

.checkbox {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
  cursor: pointer;
  accent-color: #22c55e;
}

.checkbox-placeholder {
  flex-shrink: 0;
  width: 20px;
  height: 20px;
}

.todo-content-wrapper {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 4px;
  cursor: text;
}

.todo-content {
  font-size: 14px;
  color: var(--text-primary);
  word-break: break-word;
  line-height: 1.5;
}

.todo-content.completed {
  text-decoration: line-through;
  color: var(--text-secondary);
  opacity: 0.6;
}

.todo-date {
  font-size: 12px;
  color: var(--text-secondary);
  opacity: 0.7;
}

.todo-input {
  flex: 1;
  font-size: 14px;
  padding: 0;
  border: none;
  background: transparent;
  color: var(--text-primary);
  outline: none;
  line-height: 1.5;
  width: 100%;
}

.add-todo-btn {
  cursor: pointer;
  color: var(--text-secondary);
  justify-content: flex-start;
  gap: 8px;
}

.add-todo-btn:hover {
  color: var(--text-primary);
  background: var(--bg-secondary);
}

.add-icon {
  flex-shrink: 0;
  width: 16px;
  height: 16px;
  margin-left: 2px;
}

.add-text {
  font-size: 14px;
  line-height: 1.5;
}

/* 固定在底部的添加按钮 */
.fixed-add-btn {
  position: fixed;
  bottom: 16px;
  left: 10px;
  right: 10px;
  width: calc(100% - 20px);
  z-index: 10;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}
</style>
